package scigest.metadata;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.petebevin.markdown.MarkdownProcessor;


import scigest.configuration.ConfigKeys;
import scigest.configuration.ScigestConfiguration;

/**
 * A simple readme file handler: it checks a static array of pre-defined readme names.
 * If found, the content of the files are stored in the context.
 * 
 * @author Feiyi Wang
 *
 */

public class ReadmeHandler extends MetadataHandler implements Command  {

	private static final Logger logger = LoggerFactory.getLogger(ReadmeHandler.class);
	private static final String[] readmeList = new String[] {"readme.md", "readme.txt", "readme.html"};
	private String type;

	@Autowired
	private ScigestConfiguration sc;
	

	/**
	 * Given a list of pre-defined readme files, we check their existence
	 * in the order provided. First encounter will be returned as a String.
	 * If none provided is in existence, we return null.
	 *  
	 * @return null if no file provided is in existence, otherwise, return 
	 * 		   file context as string.
	 * @throws IOException 
	 */
	private String readme2String(String[] readmeList) throws IOException {
		
		String readmeStr = null;
		List<String> aList = Arrays.asList(readmeList);
		assert sc != null;
		String dataSrc = sc.getString(ConfigKeys.DATA_SRC);
		
		for (String fname : aList) {
			File f = new File(dataSrc + "/" + fname);
			if ( f.exists() && f.isFile() ) {
				readmeStr = FileUtils.readFileToString(f);
				String ext = FilenameUtils.getExtension(fname);
				if (ext.equals("txt"))
					type = "txt";
				else if (ext.equals("md"))
					type = "markdown";
				else if (ext.equals("html"))
					type = "html";
				else { 
					logger.debug("Unknown extension [{}], use default", ext);
					type = "txt";	
				}		
				break;
			}
		}
		return readmeStr;
	}
	
	/**
	 * Convert a markdown string to html
	 * 
	 * @param str
	 * @return
	 */
	private String markdown2html(String str) {
		MarkdownProcessor mp = new MarkdownProcessor();
		String mdString = mp.markdown(str);
		return mdString;
	}
	
	@Override
	public boolean execute(Context ctx) throws Exception {
		String readmeStr  = readme2String(readmeList);
		if (readmeStr == null) {
			logger.debug("No readme is detected ... skipping");
			return false;
		} else {
			logger.debug("Found readme file, with extension of [{}]", type);
		}

		// convert to html string if configurated so.
		
		if (type.equals("markdown") && 
				sc.getCompositeConfiguration().getBoolean(ConfigKeys.MD_TOHTML, true)) {
			readmeStr = markdown2html(readmeStr);
			type = "html";
			logger.debug("Converting markdown to html");
		}
		
		ctx.put(ConfigKeys.README_CONTENT, readmeStr);
		ctx.put(ConfigKeys.README_TYPE, type);
		
		if (ingestSolr(ctx)) {
			logger.debug("Solr ingestion is successful");
		} else {
			logger.debug("Solr ingestion failed");
		}
		
		
		return false;
	}

	@Override
	public List<String> getFieldList() {
		List<String> fieldList = new ArrayList<String>();
		fieldList.add(ConfigKeys.README_TYPE);
		fieldList.add(ConfigKeys.README_CONTENT);
		return fieldList;
	}

	
}
